<template>
  <div class="main-container">
    <div class="main-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{path: '/advert/list'}">资讯信息管理</el-breadcrumb-item>
        <el-breadcrumb-item>修改资讯</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="wrap">
      <div class="content">
        <el-form class="mt-30" ref="form" :model="form" label-width="150px" style="width: 800px;">
          <div style="width:450px">
            <el-form-item label="栏目分类" prop="type"  :rules="[ { required: true, message: '必须选择分类'}]">
              <el-select v-model="form.type" style="width: 100%">
                <el-option :value="1" label="首页轮播"></el-option>
                <el-option :value="2" label="热点资讯"></el-option>
                <el-option :value="3" label="最新活动"></el-option>
                <el-option :value="4" label="营销知识"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="title" :rules="[ { required: true, message: '标题不能为空'}]">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="pc链接地址" prop="articleLink" v-if="form.type == 1">
              <el-input v-model="form.articleLink"></el-input>
            </el-form-item>
            <el-form-item label="手机链接地址" prop="phoneArticleLink" v-if="form.type == 1">
              <el-input v-model="form.phoneArticleLink"></el-input>
            </el-form-item>
            <el-form-item label="是否需要报名" prop="isSupportSignUp" v-if="form.type == 3">
              <div class="help-tip el-iconhelp_tip element-icons">
                <p class="help-tip-content">如果选择是，学员可以通过点击“报名”按钮参加活动。<br/>如果选择否，学员不通过报名也能参加活动。</p>
              </div>
              <el-switch v-model="form.isSupportSignUp" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <el-form-item label="报名截止日期" prop="signUpEndTime" v-if="form.isSupportSignUp == 1">
              <el-date-picker type="date" v-model="form.signUpEndTime" style="width:100%" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="pc封面图片" prop="titleImage">
              <el-upload
                class="avatar-uploader"
                :action="actionUrl + '?fileType=2&businessType=1'"
                :show-file-list="false"
                :on-success="imageSuccess"
                :file-list="imageList"
                >
                <img v-if="form.titleImage" :src="form.titleImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item prop="memo" style="width:700px;color:red">
              <span v-if="form.type == 1">* 建议上传图片尺寸：1920 * 600</span>
              <span v-if="form.type == 2">* 建议上传图片尺寸：250 * 150</span>
              <span v-if="form.type == 3">* 建议上传图片尺寸：250 * 150</span>
              <span v-if="form.type == 4">* 建议上传图片尺寸：250 * 150</span>
              <br/>&nbsp;&nbsp;内容放在居中1200像素区域，上下左右预留背景
            </el-form-item>
            <el-form-item label="手机封面图片" prop="phoneImage">
              <el-upload
                class="avatar-uploader"
                :action="actionUrl + '?fileType=2&businessType=1'"
                :show-file-list="false"
                :on-success="phoneImageSuccess"
                :file-list="phoneImageList"
                >
                <img v-if="form.phoneImage" :src="form.phoneImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <span v-if="form.type == 1"  style="color:red">* 建议上传图片尺寸：750 * 400</span>
              <span v-if="form.type == 2"  style="color:red">* 建议上传图片尺寸：120 * 90</span>
              <span v-if="form.type == 3"  style="color:red">* 建议上传图片尺寸：120 * 90</span>
              <span v-if="form.type == 4"  style="color:red">* 建议上传图片尺寸：120 * 90</span>
            </el-form-item>
            <el-form-item label="上传视频" v-if="form.type == 2 || form.type == 3 || form.type == 4" prop="advertVideoUrl">
              <el-upload
               
                :action="actionUrl + '?fileType=3&businessType=1'"
                :on-success="videoSuccess"
                :file-list="videoList"
                :limit="1"
                :on-remove="videoHandleRemove"
                >
                <el-button size="small" type="primary">点击上传</el-button>
                <span>如需替换文件,先删除</span>
              </el-upload>
            </el-form-item>
            <el-form-item label="是否热门" prop="isHot">
              <div class="help-tip el-iconhelp_tip element-icons" style="left: -90px;">
                <p class="help-tip-content">如果选择是，该活动可以在最新活动页面的轮播图中展示。</p>
              </div>
              <el-switch v-model="form.isHot" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            
            <el-form-item label="排序" prop="sort">
              <div class="help-tip el-iconhelp_tip element-icons" style="left: -62px;">
                <p class="help-tip-content">页面中可以通过“排序”进行倒序排序。</p>
              </div>
              <el-input-number v-model="form.sort" :min="0" :controls="false"></el-input-number>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <div class="help-tip el-iconhelp_tip element-icons" style="left: -62px;">
                <p class="help-tip-content">草稿：表示数据刚新增，页面中查询不到此数据。<br/>已发布：表示数据已经发布，页面中可以查到此数据。<br/>下线：表示数据已经下线，页面中查询不到。</p>
              </div>
              <el-select v-model="form.status" style="width: 100%">
                <el-option :value="1" label="草稿"></el-option>
                <el-option :value="2" label="已发布"></el-option>
                <el-option :value="3" label="下线"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="关键字" prop="seoKeyword">
              <el-input v-model="form.seoKeyword" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="memo">
              <el-input v-model="form.memo" type="textarea"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="详情" style="height:400px">
            <quill-editor 
              ref="myTextEditor"
              v-model="content"
              :options="editorOption"
              @change="onEditorChange($event)"
              style="height:300px">
            </quill-editor>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
        <el-upload
          :action="actionUrl + '?fileType=2&businessType=4'"
          :on-success="quillSuccess"
          style="display:none"
          >
          <el-button type="primary" id="uploadHidden">点击上传</el-button>
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script>
  import {quillEditor} from 'vue-quill-editor'
  import 'quill/dist/quill.snow.css'
  // 富文本提示
  import { addQuillTitle } from '@/libs/quill-title.js'
  export default {
    components: {
      quillEditor
    },
    data () {
      return {
        imageUrl: '',
        content: '',
        form: {
          type: '',
          title: '',
          status: '',
          advertVideoUrl: ''
        },
        imageList: [],
        phoneImageList: [],
        videoList: [],
        editorOption: {
          modules: {
           toolbar: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'font': [] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'align': [] }],
              ['clean'],
              ['link', 'image', 'video']
            ]
          }
        },
      }
    },
    activated() {
      this.form.advertId = this.$route.params.id
      this.actionUrl = this.$api.upload()
      this.getDetail()
    },
    created() {
      this.form.advertId = this.$route.params.id
      this.actionUrl = this.$api.upload()
      this.getDetail()
    },
    mounted() {
      addQuillTitle();
      this.$refs.myTextEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler);
    },
    methods: {
      imgHandler(state){
        this.addRange = this.$refs.myTextEditor.quill.getSelection()
        if (state) {
          let fileInput = document.getElementById('uploadHidden')
          fileInput.click(); // 加一个触发事件
        }
      },
      getDetail() {
        this.$api.advert.getDetail(this.form.advertId).then(res => {
          this.form = res.data
          this.content = res.data.content
          if(res.data.advertVideoUrl){
              const l = res.data.advertVideoUrl.split('/')
              const videoName = l[l.length-1];
              this.videoList = [{name: videoName, url: res.data.advertVideoUrl}]
            }
        })
      },

      onSubmit() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.$api.advert.update(this.form).then(res => {
              if(res.success) {
                this.$message.success('修改成功')
                this.$refs.form.resetFields()
                this.videoList = []
                this.$router.push('/advert/list');
              }
            })
          }
        })
      },
      onReset() {
        this.$refs.form.resetFields()
        this.content = ''
      },
      onEditorChange(editor) {
        this.form.content = this.content
        // console.log('editor blur!', editor)
      },
      onEditorChange(editor) {
        this.form.content = this.content
        // console.log('editor blur!', editor)
      },
      imageSuccess(res, file) {
        this.form.titleImage = res.data.totalUrl
        this.$forceUpdate()
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      phoneImageSuccess(res, file) {
        this.form.phoneImage = res.data.totalUrl
        this.$forceUpdate()
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      videoSuccess(res, file) {
        if(res.success) {
          this.form.advertVideoUrl = res.data.totalUrl
        } else {
          this.videoList = []
        }
      },
      quillSuccess(res, file, fileList){
        this.$message.success('上传成功');
        const imgUrl = res.data.totalUrl;
        this.$refs.myTextEditor.quill.insertEmbed(this.addRange != null ? this.addRange.index : 0, 'image', imgUrl)
      },
      videoHandleRemove(file, fileList){
        this.form.advertVideoUrl = ''
      }
    }
  }
</script>
<style lang="less">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>